package com.bluezone.dec.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bluezone.dec.common.CodeEnum;
import com.bluezone.dec.common.SystemConstant;
import com.bluezone.dec.configuration.AppConfig;
import com.c503.sc.utils.basetools.C503PropertiesUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Set;


@Component
public class RestUtils {

    private static Logger log = LoggerFactory.getLogger(RestUtils.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private AppConfig appConfig;

    /**
     * 获取dse请求路径
     *
     * @param apiUrlPropertiesKey
     * @return
     */
    public String getApiUrl(String apiUrlPropertiesKey) {

        String apiUrl = "";

        try {
            apiUrl = appConfig.getDseIp() + C503PropertiesUtils.getValue(SystemConstant.API_PROPERTIES, apiUrlPropertiesKey);
        } catch (Exception e) {
            log.info(CodeEnum.NO_PATH_IN_PROPERTIES.getMsg(), e);
        }

        return apiUrl;
    }


    public JSONArray doGet(String apiUrl) {
        return doGet(apiUrl, null);
    }

    public JSONArray doGet(String apiUrl, Map<String, Object> params) {

        /* 拼接请求URL */
        StringBuilder url = new StringBuilder(apiUrl);

        if (null != params) {

            Set<String> keySet = params.keySet();
            url.append("?");

            for (String key : keySet) {
                url.append(key + "=" + params.get(key) + "&");
            }

        }

        JSONArray data = null;

        /* 获取token */
        String token = HttpContextUtils.getHttpServletRequest().getHeader(appConfig.keyName());

        /* 将token放进请求头 */
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(appConfig.keyName(), token + "");

        /* 发起请求 */
        ResponseEntity<JSONObject> responseEntity =
                restTemplate.exchange(new String(url), HttpMethod.GET, new HttpEntity(httpHeaders), JSONObject.class);

        if (0 == responseEntity.getBody().getIntValue("code")) {
            data = responseEntity.getBody().getJSONArray("data");
        }

        return data == null ? new JSONArray() : data;
    }


}
